#nullable enable
using Godot;
using AndroidUnevenRoadGame.Game;

namespace AndroidUnevenRoadGame.UI
{
	public partial class MainMenu : Control
	{
		[Export] private Button? _startButton;
		[Export] private HBoxContainer? _buttonContainer;

		private string _selectedCharacterId = string.Empty;

		public override void _Ready()
		{
			_startButton ??= GetNode<Button>("VBox/Buttons/StartButton");
			_buttonContainer ??= GetNode<HBoxContainer>("VBox/CharacterContainer");

			PopulateCharacters();

			_startButton!.Disabled = true;
			_startButton.Pressed += OnStartPressed;
		}

		private void PopulateCharacters()
		{
			if (_buttonContainer == null)
			{
				return;
			}

			foreach (var child in _buttonContainer.GetChildren())
			{
				child.QueueFree();
			}

			foreach (var definition in CharacterDatabase.GetAll())
			{
				var button = new Button
				{
					Text = $"{definition.Name}\nHP {definition.InitialHp}",
					SizeFlagsHorizontal = SizeFlags.ExpandFill,
					ToggleMode = true,
					FocusMode = FocusModeEnum.All
				};

				button.Pressed += () => OnCharacterSelected(definition.Id, button);
				_buttonContainer.AddChild(button);
			}
		}

		private void OnCharacterSelected(string characterId, Button pressedButton)
		{
			foreach (var child in _buttonContainer!.GetChildren())
			{
				if (child is Button button && button != pressedButton)
				{
					button.ButtonPressed = false;
				}
			}

			_selectedCharacterId = characterId;
			pressedButton.ButtonPressed = true;
			_startButton!.Disabled = false;
		}

		private void OnStartPressed()
		{
			if (string.IsNullOrEmpty(_selectedCharacterId))
			{
				return;
			}

			var game = GameRoot.Instance;
			game.StartNewRun(_selectedCharacterId);
		}
	}
}

